from django.db import models

# 1. 商品大类（一级分类）
class ProductMainCategory(models.Model):
    name = models.CharField(max_length=50, unique=True, verbose_name="大类名称")
    desc = models.TextField(null=True, blank=True, verbose_name="大类描述")
    sort_order = models.IntegerField(default=0, verbose_name="排序（数字越小越靠前）")

    class Meta:
        verbose_name = "商品大类"
        verbose_name_plural = verbose_name
        db_table = "product_main_category"
        ordering = ["sort_order"]  # 按排序字段默认排序

    def __str__(self):
        return self.name

# 2. 商品小类（二级分类，关联到大类）
class ProductSubCategory(models.Model):
    main_category = models.ForeignKey(
        ProductMainCategory,
        on_delete=models.CASCADE,
        related_name="sub_categories",  # 允许通过大类查询小类：main_category.sub_categories.all()
        verbose_name="所属大类"
    )
    name = models.CharField(max_length=50, verbose_name="小类名称")
    desc = models.TextField(null=True, blank=True, verbose_name="小类描述")
    sort_order = models.IntegerField(default=0, verbose_name="排序")

    class Meta:
        verbose_name = "商品小类"
        verbose_name_plural = verbose_name
        db_table = "product_sub_category"
        ordering = ["sort_order"]
        unique_together = ["main_category", "name"]  # 同一大类下小类名称唯一

    def __str__(self):
        return f"{self.main_category.name} - {self.name}"

# 3. 商品表（单品，关联到小类）
class Product(models.Model):
    sub_category = models.ForeignKey(
        ProductSubCategory,
        on_delete=models.CASCADE,
        related_name="products",  # 允许通过小类查询商品：sub_category.products.all()
        verbose_name="所属小类"
    )
    name = models.CharField(max_length=100, verbose_name="商品名称")
    barcode = models.CharField(max_length=20, unique=True, verbose_name="商品条码")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="销售价格")
    image = models.CharField(max_length=255, null=True, blank=True, verbose_name="商品图片URL")
    stock = models.IntegerField(default=0, verbose_name="库存数量")
    is_hot = models.BooleanField(default=False, verbose_name="是否热销")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "商品"
        verbose_name_plural = verbose_name
        db_table = "product_product"

    def __str__(self):
        return self.name
